<!DOCTYPE html>
<html lang="ja">
  <head>
    <meta charset="UTF-8" />
    <title>manual</title>
    <script
      crossorigin
      src="https://unpkg.com/react@16/umd/react.development.js"
    ></script>
    <script
      crossorigin
      src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"
    ></script>
    <script
      crossorigin
      src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.34/browser.min.js"
    ></script>
    <script src="https://cdn.jsdelivr.net/npm/babel-regenerator-runtime@6.5.0/runtime.min.js"></script>
  </head>
  <body>
    <div class="main">
      <div class="section" id="app1"></div>
    </div>
    <script type="text/babel">
      let rtc;

      const App = () => {
        const [sdp, setSdp] = React.useState("");

        const signaling = async () => {
          const peer = (rtc = new RTCPeerConnection({
            iceServers: [{ urls: "stun:stun.l.google.com:19302" }],
          }));
          peer.onicecandidate = ({ candidate }) => {
            if (!candidate) {
              setSdp(JSON.stringify(peer.localDescription));
            }
          };

          const channel = peer.createDataChannel("chat");
          channel.onmessage = (ev) => {
            console.log(new TextDecoder("utf-8").decode(ev.data));
          };
          channel.onopen = () => {
            console.log("open");
            setInterval(() => {
              console.log("send");
              channel.send("ping");
            }, 1000);
          };
          channel.onclose = (e) => {
            console.log("close", e);
          };
          channel.onerror = (e) => {
            console.log("error", e);
          };

          await new Promise((r) => (peer.onnegotiationneeded = r));

          const offer = await peer.createOffer();
          await peer.setLocalDescription(offer);
        };

        React.useEffect(() => {
          signaling();
        }, []);

        const inputSdp = async (ev) => {
          const answer = JSON.parse(ev.target.value);
          console.log(answer);
          await rtc.setRemoteDescription(answer);
        };

        return (
          <div>
            offer
            <br />
            <br />
            <div>{sdp}</div>
            <input onChange={inputSdp} />
          </div>
        );
      };

      ReactDOM.render(<App />, document.getElementById("app1"));
    </script>
  </body>
</html>
